<?php

namespace App\Models\College;

use App\Models\BaseModel;
use App\Models\Common\ResourcesModel;
use App\Models\Kms\User\KmsUser;
use App\Models\Traits\KfSoftDeletes;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Kuafu\Snow\KfSnow;

class CollegeTrainingOrderUserModel extends BaseModel
{
    use KfSoftDeletes;

    protected $table = 'college_training_order_users';

    protected $fillable = [
        'examNo',
        'userId',
        'trainingOrderId',
        'cruiseOrderId',
        'examTotalScore',
        'examActualScore',
        'practiceScore',
        'examEndTime',
        'examQuestionNum',
        'examResult',
        'practiceResult',
        'finalResult',
        'isHistory',
        'isDeleted',
    ];

    const RESULT_INIT  = 0; // 初始化
    const RESULT_OK    = 1; // 通过
    const RESULT_FAIL  = 2; // 未通过
    const RESULT_CLOSE = 3; // 已关闭/超时

    const EXAM_RESULT_TEXT = [
        self::RESULT_INIT  => '待考试',
        self::RESULT_OK    => '通过',
        self::RESULT_FAIL  => '未通过',
        self::RESULT_CLOSE => '已关闭',
    ];

    public static function boot()
    {
        parent::boot();

        // where 表名.isHistory = 0
        static::addGlobalScope('isHistory', function (Builder $builder) {
            $builder->where($builder->getModel()->getTable() . '.isHistory', 0);
        });
    }

    public function trainingOrderRel(): HasOne
    {
        return $this->hasOne(CollegeTrainingOrderModel::class, 'id', 'trainingOrderId');
    }

    public static function init(int $userId, int $trainingOrderId)
    {
        CollegeTrainingOrderUserModel::query()->create([
            'examNo'          => "CP" . KfSnow::nextIdCache(),
            'userId'          => $userId,
            'trainingOrderId' => $trainingOrderId,
            'cruiseOrderId'   => 0,
            'examTotalScore'  => 0,
            'examActualScore' => 0,
            'examEndTime'     => 0,
            'examResult'      => CollegeTrainingOrderUserModel::RESULT_INIT,
        ]);
    }

    public function resourcePracticeCheckUrlsRel()
    {
        return $this->hasMany(ResourcesModel::class, 'businessId')
            ->where('module', ResourcesModel::MODULE_TYPE_COLLEGE)
            ->where('business', ResourcesModel::BUSINESS_COLLEGE_COURSES)
            ->where('name', 'practiceCheckUrls');
    }

    /**
     * @return HasOne
     */
    public function fsUserRel(): HasOne
    {
        return $this->hasOne(KmsUser::class, "rmsUserId", "userId");
    }
}
